package dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import src.User;
import util.HibernateUtil;


public class UserDao extends Dao<Object>{

	public UserDao()
	{
		super();
	}
	
	@Override
	public Object create(Object obj) {
		HibernateUtil.beginTransaction();
		HibernateUtil.save((User)obj);
		HibernateUtil.commitOrRollback();
		HibernateUtil.closeSession();
		return obj;
	}

	@Override
	public Object find(long id) {
		HibernateUtil.openSession();
		User loadedUser = (User) HibernateUtil.get(User.class, id);
		HibernateUtil.closeSession();
		return loadedUser;
	}

	@Override
	public ArrayList<Object> get() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void delete(Object obj) {
		HibernateUtil.openSession();
		HibernateUtil.save(obj);
		HibernateUtil.closeSession();
	}

	@Override
	public void update(Object obj) {
		HibernateUtil.openSession();
		HibernateUtil.update(obj);
		HibernateUtil.closeSession();
	}

	@Override
	public Object findByLogin(String login) {
		User usr = null;
		log.warn("Trying to fetch user " + login);
		
		HibernateUtil.beginTransaction();
		Criteria crit = HibernateUtil.createCriteria( User.class);
		crit.add(Restrictions.eq("loginUser", login));
		List<Object> userList = HibernateUtil.getList(crit);
		
		HibernateUtil.commitOrRollback();
		HibernateUtil.closeSession();
		
		if(userList.size() > 0)
			usr = (User) userList.get(0);
		
		return usr;
	}
}
